/* Functions for the popuplink plugin dialogue */

var PopupLinkDialogue = {
    preInit: function() {
        tinyMCEPopup.requireLangPack();
    },

    init: function() {
        tinyMCEPopup.resizeToInnerSize();

        var formObj = document.forms[0];
        var ed = tinyMCEPopup.editor;
        var elm = ed.selection.getNode();
        var action = "insert";

        document.getElementById('href').onchange = function() { PopupLinkDialogue.updateDialogue(); }
        document.getElementById('width').onchange = this.changeWidth;
        document.getElementById('height').onchange = this.changeHeight;

        document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser','href','file','popuplink');
        document.getElementById('thumbbrowsercontainer').innerHTML = getBrowserHTML('thumbbrowser','thumb','image','popuplink');

        // Resize some elements
        if (isVisible('hrefbrowser'))
        {
            document.getElementById('href').style.width = '260px';
        }

        if (isVisible('thumbbrowser'))
        {
            document.getElementById('thumb').style.width = '260px';
        }

        elm = ed.dom.getParent(elm, "A");
        if (elm != null && elm.nodeName == "A")
        {
            action = "update";
        }

        formObj.insert.value = tinyMCEPopup.getLang(action, 'Insert', true);

        if (action == "update")
        {
            var href = ed.dom.getAttrib(elm, 'href');
            var thumbSrc = '';
            var desc = '';
            if (elm.childNodes.length > 0 && elm.firstChild.nodeName == 'IMG')
            {
                thumbSrc = ed.dom.getAttrib(elm.firstChild, 'src');
                desc = ed.dom.getAttrib(elm.firstChild, 'alt');
            }

            // Setup form data
            this.setFormValue('href', href);
            this.setFormValue('thumb', thumbSrc);
            this.setFormValue('desc', desc);
            this.setFormValue('title', ed.dom.getAttrib(elm, 'title'));

            this.updateDialogue();
        }
    },

    setFormValue: function(name, value) {
        document.forms[0].elements[name].value = value;
    },

    setAttrib: function(elm, attrib, value) {
        var formObj = document.forms[0];
        var valueElm = formObj.elements[attrib.toLowerCase()];
        var dom = tinyMCEPopup.editor.dom;

        if (typeof(value) == "undefined" || value == null)
        {
            value = "";

            if (valueElm)
            {
                value = valueElm.value;
            }
        }

        dom.setAttrib(elm, attrib, value);
    },

    insertLink: function() {
        var ed = tinyMCEPopup.editor;
        var f = document.forms[0];
        var elm;

        elm = ed.selection.getNode();
        elm = ed.dom.getParent(elm, "A");

        // Remove element if there is no href
        if (!f.href.value)
        {
            tinyMCEPopup.execCommand("mceBeginUndoLevel");
            i = ed.selection.getBookmark();
            ed.dom.remove(elm, 1);
            ed.selection.moveToBookmark(i);
            tinyMCEPopup.execCommand("mceEndUndoLevel");
            tinyMCEPopup.close();
            return;
        }

        if (!f.thumb.value || !f.width.value || !f.height.value)
        {
            tinyMCEPopup.alert(tinyMCEPopup.getLang('popuplink_dlg.required_fields'));

            return;
        }

        if (!this.isImage(f.thumb.value))
        {
            tinyMCEPopup.alert(tinyMCEPopup.getLang('popuplink_dlg.invalid_thumbnail'));
        }

        tinyMCEPopup.execCommand("mceBeginUndoLevel");

        // Create new anchor elements
        if (elm == null)
        {
            ed.getDoc().execCommand("unlink", false, null);
            tinyMCEPopup.editor.execCommand('mceInsertContent', false, '<a id="__mce_tmp_url"><img /></a>', {skip_undo : 1});
            elm = ed.getDoc().getElementById("__mce_tmp_url");
            this.setLinkAttribs(elm);
            this.setAttrib(elm, 'id', '');
        } 
        else
        {
            this.setLinkAttribs(elm);
        }

        if (elm.childNodes.length > 0 && elm.firstChild.nodeName == 'IMG')
        {
            this.setImageAttribs(elm.firstChild);
        } 
        else
        {
            // create new image element
            tinyMCEPopup.editor.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
            var imgElm = tinyMCEPopup.editor.getDoc().getElementById('__mce_tmp');
            this.setImageAttribs(imgElm);
            this.setAttrib(imgElm, 'id', '');
        }

        tinyMCEPopup.execCommand("mceEndUndoLevel");
        tinyMCEPopup.close();
    },

    setLinkAttribs: function(elm) {
        var f = document.forms[0];

        var href = f.href.value;

        var parts = href.split('?');
        var query = '';
        if (parts.length > 1)
        {
            query = parts[1];

            query = /width=\d*/i.test(query)
                ? query.replace(/width=\d*/i, 'width=' + f.width.value)
                : 'width=' + f.width.value + '&' + query;
            
            query = /height=\d*/i.test(query)
                ? query.replace(/height=\d*/i, 'height=' + f.height.value)
                : 'height=' + f.height.value + '&' + query;
        }
        else
        {
            query = 'width=' + f.width.value + '&height=' + f.height.value;
        }

        href = parts[0] + '?' + query;
        
        this.setAttrib(elm, 'href', href);
        this.setAttrib(elm, 'title');
        
        var className = tinyMCEPopup.getParam("popuplink_class");
        if (className)
        {
            this.setAttrib(elm, 'class', className);
        }
    },

    setImageAttribs: function(img) {
        var formObj = document.forms[0];

        this.setAttrib(img, 'src', formObj.thumb.value);
        this.setAttrib(img, 'alt', formObj.desc.value);
    },

    changeWidth: function() {
    		var f = document.forms[0];

    		if (!PopupLinkDialogue.preloadImg || f.width.value == "" || f.height.value == "")
        {
		    	  return;
		    }

        var tp = (parseInt(f.height.value) / parseInt(PopupLinkDialogue.preloadImg.height)) * PopupLinkDialogue.preloadImg.width;
        f.width.value = tp.toFixed(0);
    },

    changeHeight: function() {
        var f = document.forms[0];

        if (!PopupLinkDialogue.preloadImg || f.width.value == "" || f.height.value == "")
        {
            return;
        }

        var tp = (parseInt(f.width.value) / parseInt(PopupLinkDialogue.preloadImg.width)) * PopupLinkDialogue.preloadImg.height;
        f.height.value = tp.toFixed(0);
    },

    resetDialogue: function() {
        var f = document.forms[0];

        f.width.value = f.height.value = "";
    },

    updateImageData: function() {
        var f = document.forms[0];

        if (f.width.value == "")
        {
            f.width.value = PopupLinkDialogue.preloadImg.width;
        }

        if (f.height.value == "")
        {
            f.height.value = PopupLinkDialogue.preloadImg.height;
        }
    },

    updateDialogue: function() {
        this.resetDialogue();

        var f = document.forms[0];
        var href = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.href.value);
        
        if ( !this.isImage(href) )
        {
            // try to extract width & height from url params
            var params = this.getUrlParams(href);
            var width = params['width'] ? params['width'] : '';
            var height = params['height'] ? params['height'] : '';

            f.width.value = width;
            f.height.value = height;
        }
        else
        {
            if ( !this.preloadImage )
            {
                this.preloadImg = new Image();
                this.preloadImg.onload = this.updateImageData;
                this.preloadImg.onerror = this.resetDialogue;
            }
            this.preloadImg.src = href;
        }
    },

    isImage: function(url) {
        // get rid of query string
        url = url.split('?');
        return /\.(jpe?g|gif|tiff?|png|bmp)$/i.test(url[0]);
    },

    getUrlParams: function(url) {
        var params = {};

        var urlParts = String(url).split('?');
        if (urlParts.length > 1)
        {
            var pos = urlParts[1].indexOf('#');
            if (pos >= 0)
            {
                urlParts[1] = urlParts[1].substring(0, pos - 1);
            }

            var nameValues = urlParts[1].split('&');
            for (i in nameValues)
            {
                var param = nameValues[i].split('=');
                params[param[0]] = param[1] ? param[1] : '';
            }
        }

        return params;
    }
};

PopupLinkDialogue.preInit();
tinyMCEPopup.onInit.add(PopupLinkDialogue.init, PopupLinkDialogue);
